package com.ys.cloudpicture.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ys.cloudpicture.constant.UserConstant;
import com.ys.cloudpicture.exception.BusinessException;
import com.ys.cloudpicture.exception.ErrorCode;
import com.ys.cloudpicture.exception.ThrowUtils;
import com.ys.cloudpicture.mapper.UserMapper;
import com.ys.cloudpicture.model.dto.user.*;
import com.ys.cloudpicture.model.entity.User;
import com.ys.cloudpicture.model.enums.UserRoleEnum;
import com.ys.cloudpicture.model.vo.UserLoginVO;
import com.ys.cloudpicture.model.vo.UserVO;
import com.ys.cloudpicture.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author YS
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-01-24 15:33:54
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @Override
    public UserLoginVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        // 1.校验数据
        ThrowUtils.throwIf(userAccount == null || userPassword == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(userLoginRequest.getUserAccount().length() < 4, ErrorCode.PARAMS_ERROR, "账号过短");
        ThrowUtils.throwIf(userLoginRequest.getUserPassword().length() < 6, ErrorCode.PARAMS_ERROR, "密码过短");
        // 2.获取密码
        String encryptPassword = getEncryptPassword(userPassword);
        // 3.查询数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        // 4.创建返回对象
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtil.copyProperties(user, userLoginVO);
        // 5.记录登录状态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return userLoginVO;
    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @Override
    public Long userRegister(UserRegisterRequest userRegisterRequest) {
        // 1.校验数据
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(userRegisterRequest.getUserAccount().length() < 4, ErrorCode.PARAMS_ERROR, "账号过短");
        ThrowUtils.throwIf(userRegisterRequest.getUserPassword().length() < 6, ErrorCode.PARAMS_ERROR, "密码过短");
        ThrowUtils.throwIf(!userRegisterRequest.getUserPassword().equals(userRegisterRequest.getCheckPassword()), ErrorCode.PARAMS_ERROR, "两次密码不一致");
        // 2.检查数据是否重复
        String userPassword = userRegisterRequest.getUserPassword();
        accountIsRepeat(userRegisterRequest.getUserAccount());
        // 3.加密密码
        String encryptPassword = getEncryptPassword(userPassword);
        // 4.保存数据库
        User user = new User();
        user.setUserAccount(userRegisterRequest.getUserAccount());
        user.setUserPassword(encryptPassword);
        user.setUserName("未命名用户");
        user.setUserRole(UserRoleEnum.USER.getValue());
        user.setUserAvatar(UserConstant.DEFAULT_AVATAR);
        boolean save = this.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "数据库错误");
        return user.getId();
    }


    /**
     * 账号重复校验
     * @param userAccount
     */
        public void accountIsRepeat(String userAccount) {
            long count = this.baseMapper.selectCount((new QueryWrapper<User>()).eq("userAccount", userAccount));
            ThrowUtils.throwIf(count > 0, ErrorCode.PARAMS_ERROR, "账号重复");
        }


    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @Override
    public Boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 根据 id 获取用户封装信息
     *
     * @param id
     * @return
     */
    @Override
    public UserVO getUserVOById(long id) {
        User user = this.baseMapper.selectById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 创建用户
     * @param userAddRequest
     * @return
     */
    @Override
    public Long createUser(UserAddRequest userAddRequest) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(userAddRequest.getUserAvatar()==null){
            userAddRequest.setUserAvatar(UserConstant.DEFAULT_AVATAR);
        }
        ThrowUtils.throwIf(userAddRequest.getUserAccount().length() < 4, ErrorCode.PARAMS_ERROR, "账号过短");
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        user.setUserPassword(getEncryptPassword(UserConstant.DEFAULT_PASSWORD));
        accountIsRepeat(userAddRequest.getUserAccount());
        boolean save = this.save(user);
        if (!save) {
             throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建失败");
        }
        return user.getId();
    }

    /**
     * 更新用户
     * @param userUpdateRequest
     * @return
     */
    @Override
    public Boolean updateUser(UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = this.baseMapper.selectById(userUpdateRequest.getId());
        BeanUtils.copyProperties(userUpdateRequest, user);
        return this.updateById(user);
    }

    /**
     * 获取用户分页QueryWrapper
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public Page<UserVO> listUserVOByPage(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = page(new Page<>(current, size),getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage= new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVOList = getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return userVOPage;
    }




    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }


    /**
     * 获取加密密码
     *
     * @param userPassword 密码
     * @return
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        if (userPassword == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");

        }
        return DigestUtils.md5DigestAsHex((userPassword + UserConstant.SALT).getBytes());
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public UserLoginVO getLoginUser(HttpServletRequest request) {
        // 获取session中用户信息
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(this.baseMapper.selectById(user.getId()), userLoginVO);
        return userLoginVO;

    }
    /**
     * 是否为管理员
     *
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(UserLoginVO user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    /**
     * 修改密码
     *
     * @param updatePasswordRequest
     * @param request
     * @return
     */
    @Override
    public Boolean updatePassword(UserUpdatePasswordRequest updatePasswordRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(updatePasswordRequest.getUserPassword()==null,ErrorCode.PARAMS_ERROR,"旧密码不能为空");
        ThrowUtils.throwIf(updatePasswordRequest.getUserPassword()==null,ErrorCode.PARAMS_ERROR,"新密码不能为空");
        if (updatePasswordRequest.getUserPassword().equals(updatePasswordRequest.getNewPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新旧密码不能相同");
        }
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        user.setUserPassword(updatePasswordRequest.getNewPassword());
        boolean b = this.updateById(user);
        return b;
    }
}




